package top.mccat.shirospring.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import top.mccat.shirospring.pojo.User;


/**
 * @author raven
 */
@Controller

public class ShiroController {
    @GetMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("shiroTest","hello shiro");
        return "index";
    }

    @GetMapping("/modify/add")
    public String toAddPage(){
        return "/modify/add";
    }

    @GetMapping("/modify/drop")
    public String toDropPage(){
        return "/modify/drop";
    }

    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @GetMapping("/login")
    public String login(String username, String password, Model model){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名错误");
        } catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
        }
        return "login";
    }

    @GetMapping("/noauth")
    public String unAuthorized(){
        return "noauth";
    }

    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
